package com.gxc.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author GongXincheng
 * @since 2019-10-12 20:04
 */
//@Component  可以直接使用该注解
public class TimeFilter implements Filter {

    @Value("${spring.application.name}")
    private String applicationName;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(this.getClass().getName() + " init -> applicationName：" + applicationName);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String url = request.getRequestURL().toString();
        if (url.contains("favicon.ico")) {
            filterChain.doFilter(request, servletResponse);
            return;
        }

        long start = System.currentTimeMillis();
        //System.out.println("Filter -> " + this.getClass().getName() + " init -> applicationName：" + applicationName);
        System.out.println("Filter -> requestUrl：" + url);
        filterChain.doFilter(request, servletResponse);
        System.out.println("Filter -> 请求时长：" + (System.currentTimeMillis() - start) + "ms");
        System.out.println("============================");
    }

    @Override
    public void destroy() {

    }
}
